<template>
  <div class="group-edit">
    <a-form :form="form"
            :label-col="{ span: 2 }"
            :wrapper-col="{ span: 22 }">
      <a-form-item label="名称"
                   required>
        <a-input allowClear
                 placeholder="请输入名称"
                 :maxLength="20"
                 v-decorator="['groupName', {
                   rules: [{
                     required: true, transform: value => value ? value.trim() : '', message: '请输入名称'
                   }]
                 }]" />
      </a-form-item>

      <a-form-item label="排序"
                   required>
        <a-input-number allowClear
                        style="width:100%;"
                        placeholder="请输入排序"
                        :min="1"
                        :maxLength="255"
                        v-decorator="['orderNo', {
                          rules: [{
                            required: true, message: '请输入排序'
                          }]
                        }]" />
      </a-form-item>
      <a-form-item label="分类"
                   required>
        <a-select v-decorator="['groupType',{rules: [{
                    required: true, message: '请选择分类'
                  }]}]"
                  placeholder="请选择">
          <a-select-option v-for="(item,index) in typeList"
                           :key="index"
                           :value="item.dictKey">
            {{ item.dictValue }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="机构">
        <a-row :gutter="16"
               type="flex">
          <a-col :span="14">
            <div class="unit-tree">
              <a-tree v-model="checkedKeysUnit"
                      checkable
                      :showIcon="true"
                      :autoExpandParent="autoExpandParent"
                      :expandedKeys="expandedKeys"
                      :selectedKeys="selectedKeys"
                      :load-data="loadTree"
                      :tree-data="treeDataUnit"
                      :checkStrictly="true"
                      @expand="onExpand"
                      @check="onCheck"
                      ref="unitTree">
                <a-icon slot="switcherIcon"
                        type="caret-down" />
                <a-icon slot="clazz"
                        type="appstore" />
                <a-icon slot="unit"
                        type="home" />
                <a-icon slot="dept"
                        type="bank" />
                <template slot="custom"
                          slot-scope="item">
                  <span>{{ item.title }} </span>
                  <span v-if="!item.isLeaf"
                        style="margin-left:15px;z-index:111;">
                    <!-- v-if="!item.checked" -->
                    <span title="全选">
                      <a-icon type="plus-square"
                              @click="addClick(item)" />
                    </span>
                    <span title="取消全选"
                          style="margin-left:10px;">
                      <a-icon type="minus-circle"
                              @click="cancelClick(item)" />
                    </span>
                  </span>

                </template>
              </a-tree>
            </div>
          </a-col>
          <a-col :span="10">
            <div class="unit-tag-panel">
              <div class="unit-tag-list clearfix">
                <div class="unit-tag-item"
                     v-for="(tag,index) in selectData"
                     :key="index">
                  <a-tag closable
                         @close="onRemove(tag,index)">
                    {{ tag.title }}
                  </a-tag>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>

      </a-form-item>
      <a-form-item label=""
                   :colon="false">
        <div style="text-align:center">
          <a-button v-if="groupsId!=''"
                    @click="handleDelete"
                    style="margin-right:20px;">删除</a-button>
          <a-button type="primary"
                    @click="handleSave">保存</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import 'ant-design-vue/es/tree-select/style/index.less'
import { getGroupAndUnitsById, deleteGroup, saveOrUpdateGroupInfo, init } from '../../api/unit/group'
import { getUnitTreeNodesByParentId } from '../../api/unit/index'
import { getCodeListByCode } from '../../api/dictionary/index'
export default {
  inject: ['updateModalShow'],
  props: {
    groupsId: {
      // 分组id
      type: String,
      default: ''
    },
    groupOrderNo: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      form: this.$form.createForm(this),
      selectSetting6: {
        mode: 'default', // multiple default
        url: 'system/SysDict/queryList',
        param: { code: 'GGLX' }, // code表的workid
        optionValue: 'dictKey',
        optionKey: 'dictValue',
        method: 'post'
      },
      status: true,
      unitId: [], // 机构id
      // groupName: '', // 分组名称
      // groupType: '', // 分组类型
      orderNo: null, // 排序
      // 机构相关字段
      treeData: [], // 机构数组
      count: 0,
      autoExpandParent: false,
      expandedKeys: [],
      selectedKeys: [],
      // checkedKeys: [], // 选中的节点
      checkedKeysUnit: {
        // 选中的节点
        checked: [],
        halfChecked: []
      },
      // unitReplaceFields: { key: 'id', title: 'name' },
      treeDataUnit: [], // 机构树
      typeList: [], // 分类数组
      selectData: [] // 右边显示
    }
  },
  watch: {
    checkedKeysUnit: {
      handler (val) {
        this.unitId = val.checked
      },
      deep: true
    },
    groupsId (newVal, oldVal) {
      if (newVal != oldVal) {
        this.checkedKeys = []
        this.form.setFieldsValue({})
      }
      if (this.groupsId != '') {
        this.getInfoByid(this.groupsId)
      }
    }
  },
  created () {
  },
  mounted () {
    this.form.setFieldsValue({})
    this.checkedKeys = []
    this.loadTree()
    if (this.groupsId != '') {
      this.getInfoByid(this.groupsId)
    } else {
      init().then(res => {
        this.form.setFieldsValue({ orderNo: res.orderNo })
      })
    }
    this.getTypeName('GGLX')
  },
  methods: {
    getTypeName (key) {
      getCodeListByCode({ code: 'GGLX' })
        .then((res) => {
          this.typeList = res
        })
    },
    onExpand (expandedKeys, info) {
      this.autoExpandParent = false
      this.expandedKeys = expandedKeys
    },
    // 点击复选框触发
    onCheck (checkedKeys, info) {
      this.checkedKeysUnit.checked = checkedKeys.checked
      if (info.checked) {
        let o = this.selectData.map((i) => {
          return i.value != info.node.value
        })
        if (o) {
          this.selectData.push({
            value: info.node.dataRef.value,
            title: info.node.dataRef.title
          })
        }
      } else {
        let o = []
        this.selectData.map((i) => {
          if (i.value != info.node.value) {
            o.push(i)
          }
        })
        this.selectData = o
      }
    },
    // 全选
    addClick (item) {
      Promise.all([this.loadTree(item)]).then((res) => {
        this.autoExpandParent = true
        this.getClick(item, 'add')
      })
    },
    // 取消全选
    cancelClick (item) {
      Promise.all([this.loadTree(item)]).then((res) => {
        this.getClick(item, 'del')
        this.selectedKeys = []
      })
    },
    getClick (data, type) {
      if (type === 'add') {
        if (this.checkedKeysUnit.checked.indexOf(data.key) == -1) {
          this.checkedKeysUnit.checked.push(data.key)
          let o = this.selectData.map((i) => {
            return i.value != data.key
          })
          if (o) {
            this.selectData.push({
              value: data.value,
              title: data.title
            })
          }
        }
        const addchildren = data.dataRef ? data.dataRef.children : data.dataRef
        if (addchildren && addchildren.length > 0) {
          for (let i = 0; i < addchildren.length; i++) {
            const addData = addchildren[i]
            this.getClick(addData, 'add')
          }
        }
      } else {
        let o = []
        this.selectData.map((i) => {
          if (i.value != data.key) {
            o.push(i)
          }
        })
        this.selectData = o
        if (this.checkedKeysUnit.checked.indexOf(data.key) >= 0) {
          this.checkedKeysUnit.checked = this.checkedKeysUnit.checked.filter(
            (k) => k !== data.key
          )
        }
        const delchildren = data.dataRef ? data.dataRef.children : data.dataRef
        if (delchildren && delchildren.length > 0) {
          for (let i = 0; i < delchildren.length; i++) {
            const delData = delchildren[i]
            this.getClick(delData, 'del')
          }
        }
      }
    },
    // 机构树懒加载
    loadTree (treeNode) {
      return new Promise((resolve, reject) => {
        let that = this
        let id = !treeNode ? 0 : treeNode.dataRef.value
        getUnitTreeNodesByParentId([{ id: id }])
          .then((res) => {
            resolve()
            let data = res.map((item) => {
              return {
                value: item.id,
                title: item.name,
                key: item.id,
                parentId: item.parentId,
                scopedSlots: {
                  title: 'custom',
                  icon: 'icon'
                }
              }
            })
            if (treeNode) {
              if (data && data.length > 0) {
                treeNode.dataRef.children = data
              }
              that.treeDataUnit = [...that.treeDataUnit]

              // if (treeNode.checked) {
              //   let key = treeNode.dataRef.children.map((e) => {
              //     return e.key
              //   })
              //   this.checkedKeysUnit.checked =
              //     this.checkedKeysUnit.checked.concat(key)
              // }
            } else {
              that.treeDataUnit = data
            }
          })
      })
    },
    // 删除tag
    onRemove (item, index) {
      let that = this
      let rs = that.checkedKeysUnit.checked.findIndex((c) => c == item.value)
      let keys = [...that.checkedKeysUnit.checked]
      keys.splice(rs, 1)
      this.selectData.splice(index, 1)
      that.checkedKeysUnit.checked = keys
      // that.$refs.tree.$forceUpdate()
    },
    // 根据id返回分组信息
    getInfoByid (id) {
      let that = this
      getGroupAndUnitsById(id).then((res) => {
        that.statusBool = res.status
        that.orderNo = res.orderNo
        let ids = []
        let unitArr = []
        res.unitGroupsList.forEach((item) => {
          ids.push(item.unitId)
          unitArr.push({
            value: item.unitId,
            title: item.unitName
          })
        })
        that.form.setFieldsValue(res)
        // that.checkedKeys = ids
        this.checkedKeysUnit.checked = ids
        this.unitId = ids
        this.selectData = unitArr
      })
    },
    // 保存
    handleSave (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        if (values.groupName) {
          values.groupName = values.groupName.trim()
        }

        /* if (this.unitId.length == 0) {
          this.message.warn('请选择部门')
          return
        } */
        if (this.groupsId == '') {
          values.status = true
          values.groupsId = ''
        } else {
          values.status = this.statusBool
          values.groupsId = this.groupsId
        }
        values.sysUnitGroupsList = [...new Set(this.unitId)]
        saveOrUpdateGroupInfo(values).then((res) => {
          // this.message.info(this.groupsId != '' ? '修改成功！' : '新增成功！')
          this.updateModalShow(false)
        })
      })
    },
    // 删除
    handleDelete () {
      deleteGroup(this.groupsId).then((res) => {
        // this.message.info('删除成功！')
        this.updateModalShow(false)
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ant-select-selection--single {
  height: 32px;
}
.clearfix:after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1;
}
.unit-tree {
  height: 300px;
  border: 1px solid #d9d9d9;
  overflow: auto;
}
.unit-btn {
  margin-top: 118px;
  text-align: center;
}
.unit-tag {
  &-panel {
    height: 300px;
    padding: 10px 10px;
    overflow: auto;
    border: 1px solid #d9d9d9;
  }
  &-item {
    float: left;
    margin-right: 10px;
  }
}
</style>